package com.ComputerSales.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ComputerSales.entity.Cart;
import com.ComputerSales.entity.Product;
import com.ComputerSales.entity.User;
import com.ComputerSales.service.ICartService;
import com.ComputerSales.service.IProductService;
import com.ComputerSales.service.IUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.hamcrest.collection.IsIterableContainingInAnyOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IProductService productService;

    @Autowired
    private ICartService cartService;

    @Autowired
    private IUserService userService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @GetMapping("/")
    public String index(Model model,@RequestParam(required = false) String keyword) {
        List<Product> products;
        if (keyword==null||keyword.isEmpty()) {
            products = productService.list();
        } else {
            products = productService.list(new QueryWrapper<Product>()
                    .like("name", keyword));
        }
        model.addAttribute("products", products);
        return "index";
    }

    @GetMapping("/logout")
    public String logout() {
        StpUtil.logout();
        return "redirect:/login";
    }

    @GetMapping("/userinfo")
    public String userinfo(Model model) {
        User user = userService.getById(StpUtil.getLoginIdAsInt());
        user.setPassword("");
        model.addAttribute("user", user);
        return "user/userinfo";
    }

    @GetMapping("/cart")
    public String userCart(Model model) {
        List<Cart> cartList = cartService.list(new QueryWrapper<Cart>()
                .eq("user_id", StpUtil.getLoginIdAsInt()));
        model.addAttribute("carts", cartList);
        return "user/cart";
    }


}
